package com.snow.datasource.strategy.manage.impl;

import com.snow.datasource.properties.SnowFlakeProperties;
import com.snow.datasource.strategy.IStrategy;
import com.snow.datasource.strategy.annoation.Strategy;
import com.snow.datasource.strategy.manage.ManageStrategy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description
 * @Author fanxl
 * @Date 2020/12/24
 **/
public class ManageStrategyImpl implements ApplicationContextAware, ManageStrategy, BeanPostProcessor {
    @Autowired
    private SnowFlakeProperties snowFlakeProperties;
    /**
     * 处理类集合
     */
    private Map<String, IStrategy> handlerMap = new ConcurrentHashMap<>(16);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String,Object> beans = applicationContext.getBeansWithAnnotation(Strategy.class);
        if (beans != null && beans.size() > 0) {
            for (Object serviceBean : beans.values()) {
                Strategy handlerType = AnnotationUtils.findAnnotation(serviceBean.getClass(),Strategy.class);
                handlerMap.put(handlerType.value().getType(),(IStrategy) serviceBean);
            }
        }
    }

    @Override
    public String handle() {
        return handlerMap.get(snowFlakeProperties.getStrategy()).getSlaveKey();
    }
}
